package top.goldenyear.porpoise.dev.code.service;

import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.easy.query.core.proxy.sql.Select;
import com.easy.query.solon.annotation.Db;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import top.goldenyear.porpoise.common.core.exception.ErrorCode;
import top.goldenyear.porpoise.common.core.exception.ServiceException;
import top.goldenyear.porpoise.common.core.model.PlainOption;
import top.goldenyear.porpoise.dev.code.model.CodeColumn;
import top.goldenyear.porpoise.dev.code.model.proxy.CodeColumnProxy;
import top.goldenyear.porpoise.framework.web.core.annotation.Deform;
import top.goldenyear.porpoise.framework.web.core.model.PageResult;
import top.goldenyear.porpoise.framework.web.core.model.query.QPage;
import top.goldenyear.porpoise.framework.web.core.service.BaseService;

/**
 * 字段配置 Service 服务层
 *
 * @author airhead
 * @since 2025-02-04
 */
@Component
@Slf4j
public class CodeColumnService extends BaseService<CodeColumn, CodeColumnProxy> {
  @Db private EasyEntityQuery easyEntityQuery;

  public CodeColumnService() {
    super(CodeColumn.class, CodeColumnProxy.class);
  }

  public Boolean createCodeColumn(CodeColumn codeColumn) {
    return save(codeColumn);
  }

  public Boolean updateCodeColumn(CodeColumn codeColumn) {
    return updateById(codeColumn, true);
  }

  public CodeColumn getCodeColumn(Long id) {
    return getById(id);
  }

  public Boolean deleteCodeColumn(Long id) {
    if (getById(id) == null) {
      throw new ServiceException(ErrorCode.builder().msg("记录不存在").build());
    }

    return deleteById(id);
  }

  public Boolean batchDelCodeColumn(List<Long> ids) {
    for (Long id : ids) {
      if (getById(id) == null) {
        throw new ServiceException(ErrorCode.builder().msg("记录不存在").build());
      }
    }

    return deleteByIds(ids);
  }

  public List<CodeColumn> listCodeColumn(CodeColumn codeColumn) {
    return list(codeColumn);
  }

  @Deform(keep = {"id", "name"})
  public List<CodeColumn> simpleListCodeColumn(CodeColumn codeColumn) {
    return list(codeColumn);
  }

  public List<PlainOption> optionsCodeColumn(CodeColumn codeColumn) {
    return entityQueryable()
        .select(
            PlainOption.class,
            codeColumnProxy -> Select.of(codeColumnProxy.id().as("value"), codeColumnProxy.name()))
        .toList();
  }

  public PageResult<CodeColumn> paginateCodeColumn(QPage qPage, CodeColumn codeColumn) {
    return paginate(qPage, codeColumn);
  }

  public List<CodeColumn> listByTableId(Integer tableId) {
    return entityQueryable().where(codeColumn -> codeColumn.tableId().eq(tableId)).toList();
  }

  public Boolean deleteByTableId(Integer tableId) {
    return entityDeletable().where(codeColumn -> codeColumn.tableId().eq(tableId)).executeRows()
        > 0;
  }

  @Override
  protected EasyEntityQuery easyEntityQuery() {
    return easyEntityQuery;
  }
}
